package com.itcoon.cloud.framework.redis.config;/**
 * @author Athric Yu
 * 2024/12/9
 **/

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itcoon.cloud.framework.redis.lock.RedissonDistributedLocker;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionManager;

/**
 *
 *
 * @author Athric Yu
 * 2024/12/9
 **/
@AutoConfiguration
public class RedissonAutoConfiguration implements RedissonAutoConfigurationCustomizer {

    private final ObjectMapper objectMapper;

    public RedissonAutoConfiguration(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }


    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory, ObjectMapper objectMapper) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);

        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);
        redisTemplate.setValueSerializer(jsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    @ConditionalOnBean({TransactionManager.class})
    public RedissonDistributedLocker redissonDistributedLocker(RedissonClient redissonClient, PlatformTransactionManager transactionManager){
        return new RedissonDistributedLocker(redissonClient, transactionManager);
    }

    @Override
    public void customize(Config configuration) {
        configuration.setCodec(new JsonJacksonCodec(objectMapper));
    }


}
